package com.wuhunyu;

import java.io.*;
import java.util.Objects;

/**
 * 自定义类加载器
 *
 * @author gongzhiqiang
 * @version 1.0
 * @date 2021/11/3 10:11
 */

public class MyClassLoader extends ClassLoader {

    @Override
    protected Class<?> findClass(String name) {
        String fullClassName = this.getClass().getResource("/com/wuhunyu/").getPath() + name + ".class";
        try (
                FileInputStream fileInputStream = new FileInputStream(fullClassName);
                BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()
        ) {
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = bufferedInputStream.read(bytes)) != -1) {
                byteArrayOutputStream.write(bytes, 0, len);
            }
            byte[] res = byteArrayOutputStream.toByteArray();
            return this.defineClass(null, res, 0, res.length);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
